<template>
  <div class="proplanbox">
    <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
        <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="用电企业">
                  <FilterSelect 
                      ref="yonghu" 
                      :optionlist="yonghulist" 
                      :valuekey="{name:'name',value:'id'}"
                      @changeselect="getchanping"
                      :defaultvalue="companyId"
                      ></FilterSelect>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="产品">
                  <el-select v-model="productId" placeholder="请选择用电单位"  size="small" style="width: 100%;" >
                    <el-option v-for="(item,index) in chanpinglist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="月份">
                  <el-date-picker v-model="month" type="month" value-format="yyyy-MM" placeholder="选择月份" size="small" style="width:100%;"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="9" style="text-align: right;">
                <el-form-item label="">
                  <el-button size="small"  @click="chongzhi">重 置</el-button>
                  <el-button size="small" type="primary"  @click="getdatalist">查 询</el-button>
                </el-form-item>
              </el-col>
          </el-row>
      </el-form>
    </div>
     <!-- 盒子主体 -->
     <div class="bodybox">
      <!-- 导出部分 -->
      <div class="top">
        <div>生产计划维护</div>
        <div class="butti">
          <span><el-button size="small" style="margin-right: 10px;" type="primary" @click="piliangadd"><i class="el-icon-plus"></i>批量新增生产计划</el-button></span>
          <span><el-button size="small" type="primary" @click="add"><i class="el-icon-plus"></i>新增生产计划</el-button></span>
          <TopTooltip @command="command"  @shuaxin="shuaxin"></TopTooltip>
        </div>
      </div>
      <!-- table表格 -->
      <div class="table">
        <TableColumn
        ref="tabledata"
        :tableData="tableData" 
        :tableConfig="tableConfig" 
        :issize="issize">
        <el-table-column
            prop="address"
            label="操作"
            align="center"
            width="100">
            <template #default="{row}">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <i @click="bianji(row)" class="el-icon-edit" style="color:#1a90fe ;margin-right: 20px; cursor: pointer;"></i>
               </el-tooltip>
               <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i @click="del(row)" class="el-icon-delete" style="color: red;cursor: pointer;"></i>
               </el-tooltip>
            </template>
          </el-table-column>
        </TableColumn>
          <!-- 底部分页 -->
          <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj.pageNo"
                :page-size="15"
                @current-change="getdatalist"
                :total="+totalCount">
          </el-pagination>
        </div>
      </div>
      <!-- dialog新增/修改弹窗 -->
      <div>
        <el-dialog
          title="生产计划维护"
          :visible.sync="dialogVisible"
          width="40%">
          <div>
            <el-form ref="form" :model="form" label-width="100px">
               <el-row>
                 <el-col :span="24">
                   <el-form-item label="用电企业" prop="companyId">
                    <el-select v-model="form.companyId" placeholder="请选择用电单位"  size="small" style="width: 100%;" @change="diachange">
                      <el-option v-for="(item,index) in yonghulist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                    </el-select>
                   </el-form-item> 
                 </el-col>
               </el-row>
               <el-row>
                 <el-col :span="24">
                   <el-form-item label="产品" prop="productId">
                    <el-select v-model="form.productId" placeholder="请选择用电单位"  size="small" style="width: 100%;" >
                      <el-option v-for="(item,index) in diachanpinglist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                    </el-select>
                   </el-form-item> 
                 </el-col>
               </el-row>
               <template v-if="!isshow">
                <el-row >
                  <el-col :span="24">
                    <el-form-item label="日期 从">
                      <el-date-picker v-model="form.startDate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期" size="small" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row >
                  <el-col :span="24">
                    <el-form-item label="至">
                      <el-date-picker v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期" size="small" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
               </template>
               <template v-else>
                <el-row >
                  <el-col :span="24">
                    <el-form-item label="日期">
                      <el-date-picker v-model="form.produceDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" size="small" style="width: 100%;"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
               </template>
               <el-row>
                 <el-col :span="24">
                   <el-form-item label="关联生产设备">
                    <el-select v-model="formdata.treename" multiple size="small" style="width: 100%;" @remove-tag="removetag">
                      <el-option value="treeDataValue" label="label" style="height: auto">
                        <el-tree
                          ref="tree"
                          :props="propss"
                          :highlight-current="true"
                          @node-click="handleNodeClicks"
                          :load="loadNodes"
                          lazy>
                          <template slot-scope="{ node, data }">
                            <span :style="{cursor: data.className!=='EcmEquip' ? 'no-drop' : 'pointer', fontSize: '14px'}">{{ node.label }}</span>
                          </template>
                        </el-tree>
                      </el-option>
                    </el-select>
                   </el-form-item>
                 </el-col>
               </el-row>
               <el-row >
                 <el-col :span="24">
                  <el-form-item label="生产班组">
                    <el-select v-model="form.teamId" placeholder="请选择生产班组"  size="small" style="width: 100%;" >
                      <el-option v-for="(item,index) in banzulist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                    </el-select>
                  </el-form-item>
                 </el-col>
               </el-row>
               <el-row>
                 <el-col :span="24">
                   <el-form-item label="计划量产" prop="planValue">
                    <el-input v-model="form.planValue" placeholder="请输入计划量产"  size="small" style="width: 100%;"></el-input>
                   </el-form-item> 
                 </el-col>
               </el-row>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="quxiao" size="small">取 消</el-button>
            <el-button type="primary" @click="submit" size="small">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import FilterSelect from '@/components/FilterSelect'
import { getgenjiedianapi, getzijidianapi} from '@/api/monitor'
import TopTooltip from '@/components/TopTooltip/index.vue'
import TableColumn from '@/components/Table/index.vue'
import {getprodatalistapi} from '@/api/energy-consumption/Allocation-Administration/product'
import { getyongdianlistapi } from '@/api/energy-consumption/Basic-information/medium'
import { getjihualistapi ,postaddlistapi,postpiliangaddapi,postupdatalistapi,postdellistapi} from '@/api/energy-consumption/Allocation-Administration/ProductionPlan'
import {gettablelistapi} from '@/api/energy-consumption/Allocation-Administration/Scheduling'
export default {
  name: 'CallPoliceInde',
  components: {
    TopTooltip,
    TableColumn,
    FilterSelect
  },
  data() {
    return {
      isshow:true,
      form:{},
      yonghulist: [],
      dialogVisible:false,
      companyId: '',
      month: '',
      productId: '',
      chanpinglist: [],
      issize: 'medium',
      tableData: [],
      tableConfig: [
      { label: '序号', type: 'index', center: 'center', width: '70' },
        { label: '用电企业', prop: 'companyName' ,width:'250'},
        { label: '生成日期', prop: 'produceDate' ,center:'center' },
        { label: '产品', prop: 'productName' },
        { label: '产品单位', prop: 'productUnit',center:'center' },
        { label: '生产单元', prop: 'equipNames',width:'300'},
        { label: '生产班组', prop: 'teamName'},
        { label: '计划量产', prop: 'planValue',center:'right'},
      ],
      totalCount: '',
      pageobj: {
        pageNo: 0,
        pageSize:15
      },
      diachanpinglist:[],
      banzulist: [],
      propss: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      formdata: {
        treeclassName: [],
        treename: [],
        treeclassId:[]
      },
      treevaluelist:[]
    };
  },

  async mounted() {
    // 获取用电单位
    const {data:{list}} = await getyongdianlistapi()
    this.yonghulist = list
    const companyId = localStorage.getItem('companyId')
    this.$set(this,'companyId',companyId?+companyId:'')
    this.getchanping(this.companyId)
    this.getdatalist()
  },

  methods: {
    // 弹窗确认
    async submit() {
      const array = this.formdata.treeclassId.map((item,index) => {
         return item+'_'+this.formdata.treeclassName[index]
      })
      if (this.form.id) {
        await postupdatalistapi({ ...this.form, equipIds: array.join(',') }).then(res => {
          this.$message({
            type: res.code == '200' ? 'success' : 'warning',
            message:res.code == '200' ? '修改成功' :res.message,
          })
        })
      } else {
        this.isshow? await postaddlistapi({ ...this.form, equipIds: array.join(',') }).then(res => {
          this.$message({
            type: res.code == '200' ? 'success' : 'warning',
            message:res.code == '200' ? '新增成功' :res.message,
          })
        }):await postpiliangaddapi({ ...this.form, equipIds: array.join(',') }).then(res => {
          this.$message({
            type: res.code == '200' ? 'success' : 'warning',
            message:res.code == '200' ? '批量新增成功' :res.message,
          })
        })
      }
      this.quxiao()
      this.getdatalist()
    },
    // 弹窗取消
    quxiao() {
      this.dialogVisible = false
      this.form = {}
      this.formdata.treeclassName=[]
      this.formdata.treeclassId=[]
      this.formdata.treename = []
      this.diachanpinglist=[]
      this.banzulist=[]
     },
    // 批量新增
    piliangadd() {
      this.dialogVisible = true
      this.isshow = false
      this.$set(this.form,'companyId',this.companyId)
      this.diachange(this.companyId)
    },
    // 新增
    add(){
      this.dialogVisible = true
      this.isshow = true
      this.$set(this.form,'companyId',this.companyId)
      this.diachange(this.companyId)
    },
    // 重置
    chongzhi() {
      this.companyId=''
      this.month=''
      this.productId = ''
      this.getdatalist()
    },
    // 获取表格数据
    async getdatalist() { 
      this.$refs.tabledata.loading=true
      const { data: { list, totalCount } } = await getjihualistapi({
        pageNo: this.pageobj.pageNo - 1,productId:this.productId,month:this.month,
        pageSize: this.pageobj.pageSize,companyId:this.companyId,
      })
      this.totalCount = totalCount
      this.tableData = list
      this.$refs.tabledata.loading=false
    },
    // 多选数选择
    handleNodeClicks(data, node, nodeData) {
      // 判断节点classname是否为EcmEquip，如果不是return出去 不予执行添加操作
      if(data.className!=='EcmEquip') return
      this.formdata.treeclassName.push(data.className)
      this.formdata.treeclassId.push(data.id)
      this.formdata.treename.push(data.name)
      this.treevaluelist=this.formdata.treename
    },
    // 删除多选项
    removetag(val) {
      let indexToDelete = this.treevaluelist.indexOf(val)
      if (indexToDelete > -1) {
        this.treevaluelist.splice(indexToDelete, 1)
        this.formdata.treeclassId.splice(indexToDelete, 1);
        this.formdata.treeclassName.splice(indexToDelete, 1); 
      }
    },
    // 删除
    del(row) {
      this.$confirm('此操作将永久删除该配置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await postdellistapi({ id: row.id }).then(res => {
            this.$message({
              type: res.code == '200' ? 'success' : 'warning',
              message:res.code=='200'?'删除成功':res.message
            })
          })
          this.getdatalist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑
    async bianji(row) { 
      this.dialogVisible = true
      this.isshow = true
      const {productId,teamId,...obj}=row
      this.form = obj
      this.treevaluelist = row.equipNames.split(',')
      this.formdata.treename = row.equipNames.split(',')
      this.formdata.treeclassId=row.equipIds.split(',').map(item => {
          const [number, name] = item.split("_");
          return number;
      })
      this.formdata.treeclassName=row.equipIds.split(',').map(item => {
          const [number, name] = item.split("_");
          return name;
      })
      await this.diachange(row.companyId)
      this.$set(this.form,'teamId',row.teamId)
      this.$set(this.form, 'productId', row.productId)
    },
    // 弹窗企业下拉获取产品
    async diachange(val) {
      const { data: { list } } = await getprodatalistapi({pageNo:0,level:'',
        pageSize: 500,companyId:val,})
      this.diachanpinglist = list
      const res = await gettablelistapi({
        pageNo: 0, pageSize: 500, companyId:val,teamId:''
      })
      this.banzulist=res.data.list
    },
    // 获取产品
    async getchanping(val) {
      this.$set(this,'companyId',val)
      localStorage.setItem('companyId', val)
      const { data: { list } } = await getprodatalistapi({
        pageNo:0,level:'',
        pageSize: 500,companyId:val,
      })
      this.chanpinglist=list
    },
    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 列表刷新
    shuaxin() {
      this.getdatalist()
      this.$message.success('列表刷新成功')
    },
    // 设备树懒加载
    async loadNodes (node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'ENERGY_FACTORY_SET_TREE' })
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) { // 初始的级数（最顶层）
        this.$store.commit('setmonitordata', ress.data.list[0])
        return resolve(ress.data.list) // 最顶层数据渲染为region
      }
      if (node.level === 1) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 3) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 4) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 5) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 6) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }else if (node.level === 7) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
  },
};
</script>

<style scoped>
.proplanbox{
  height: 100%;
  padding: 10px;
  .topbox{
    height: 80px;
    padding: 20px;
    background-color: #fff;
    margin-bottom: 10px;
  }
  .bodybox{
    height: calc(100% - 90px);
    margin-top: 10px;
    background-color: #fff;
    padding: 20px;
    .top{
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .butti{
        display: flex;
        align-items: center;
      }
    }
    .table{
      height: 90%;
      .fenye{
        text-align: right;
        margin-top: 10px;
      }
    }
  }
}
::v-deep .el-dialog__footer{
  text-align: center;
}
::v-deep .el-form-item{
  margin-bottom: 10px;
}
</style>